package com.youlai.boot.system.controller;

import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.config.BatchUpdateRequest;
import com.youlai.boot.config.BatchUpdateRequeste;
import com.youlai.boot.system.model.dto.PatientDTO;
import com.youlai.boot.system.model.entity.Patient;
import com.youlai.boot.system.model.entity.TaskTable;
import com.youlai.boot.system.model.query.TaskTableQuery;
import com.youlai.boot.system.model.vo.TaskTableVO;
import com.youlai.boot.system.service.PatientService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.youlai.boot.system.model.form.PatientForm;
import com.youlai.boot.system.model.query.PatientQuery;
import com.youlai.boot.system.model.vo.PatientVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import jakarta.validation.Valid;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 患者信息前端控制层
 *
 * @author
 * @since 2025-03-03 16:25
 */
@Tag(name = "患者信息接口")
@RestController
@RequestMapping("/api/v1/patients")
@RequiredArgsConstructor
public class PatientController  {

    private final PatientService patientService;

    @Operation(summary = "患者信息分页列表")
    @GetMapping("/page")
//    @PreAuthorize("@ss.hasPerm('system:patient:query')")
    public PageResult<PatientVO> getPatientPage(PatientQuery queryParams ) {
        IPage<PatientVO> result = patientService.getPatientPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "新增患者信息")
    @PostMapping("/save")
//    @PreAuthorize("@ss.hasPerm('system:patient:add')")
    public Result<Void> savePatient(@RequestBody @Valid PatientForm formData ) {
        boolean result = patientService.savePatient(formData);
        return Result.judge(result);
    }

    @Operation(summary = "获取患者信息表单数据")
    @GetMapping("/{patientId}/form")
//    @PreAuthorize("@ss.hasPerm('system:patient:edit')")
    public Result<Patient> getPatientForm(
            @Parameter(description = "患者信息ID") @PathVariable Long patientId
    ) {
        Patient formData = patientService.getPatientFormData(patientId);
        return Result.success(formData);
    }

    @Operation(summary = "修改患者信息")
    @PutMapping(value = "/{id}")
    //@PreAuthorize("@ss.hasPerm('system:patient:edit')")
    public Result<Void> updatePatient(
            @Parameter(description = "患者信息ID") @PathVariable Long id,
            @RequestBody @Validated PatientForm formData
    ) {
        boolean result = patientService.updatePatient(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除患者信息")
    @DeleteMapping("/{id}")
//    @PreAuthorize("@ss.hasPerm('system:patient:delete')")
    public Result<Void> deletePatients(
            @Parameter(description = "患者信息ID，多个以英文逗号(,)分割") @PathVariable String id
    ) {
        boolean result = patientService.deletePatients(id);
        return Result.judge(result);
    }
    /**
     * 归档接口
     * @param archive
     * @return
     */
    @PutMapping("/{id}/archive")
    public Result<Void>  updateArchiveStatus(@PathVariable Long id,@RequestParam Integer archive){
        if (archive !=0 && archive != 1){
            return Result.error("nvalid archive status. Must be 0 or 1.");
        }
        boolean result = patientService.updateArchive(id, archive);
        if (result){
            return Result.success("Update successful.");
        }else {
            return Result.error("Failed to update archive status.");
        }
    }

    /**
     * 批量归档接口
     */
    @PutMapping("/batch")
    public Result<Void> batchUpdateArchiveStatus(@RequestBody BatchUpdateRequeste request){
        if(request.getPatientId() == null || request.getPatientId().isEmpty()
                || (request.getArchive() != 0 && request.getArchive() != 1)){
            return Result.error("Invalid input.");
        }

        boolean result = patientService.batchUpdateArchiveStatus(request.getPatientId(), request.getArchive());
        if (result) {
            return Result.success("Batch update successful.");
        } else {
            return Result.error("Failed to batch update archive status.");
        }
    }

    /**
     * 年龄分布
     * @return
     */

    @GetMapping("/age-groups")
    public Result<List<PatientDTO>> getPatientCountsByAgeGroup() {
        List<PatientDTO> result = patientService.getPatientCountByAgeGroups();
        return Result.success(result);
    }

    /**
     * 查询所有已归档任务
     */
//    @GetMapping("/archivetasks")
//    public List<Patient> getArchiveTasks(){
//        return patientService.getArchiveTasks();
//    }
    @GetMapping("/archivetasks")
    public PageResult<PatientVO> getArchiveTasks(PatientQuery queryParams){
        IPage<PatientVO> result = patientService.getArchivePage(queryParams);
        return PageResult.success(result);
//        return Result.success(tasktableService.getArchiveTasks());
    }

    /**
     * 性别统计图
     * @return
     */
    @GetMapping("/gender")
    public Result<List<Map<String,Object>>> getGenderCount(){
        return Result.success(patientService.getGenderCount());
    }

    @GetMapping("conter")
    @Operation(summary = "查看所有任务")
    public Result<Integer> getAllTasktable(){
        Integer conter = patientService.getTotalDoctors();
        return Result.success(conter);
    }

    /**
     *查询过去7天的患者
     * @return
     */

    @GetMapping("weekCount")
    public Result<?> getLastWeekPatientCount(){
        long count = patientService.countPatientsByDateRange(LocalDateTime.now());
        return Result.success(count);
    }

    /**
     * 手术总次数统计
     * @return
     */
    @PostMapping("/countOperations")
    public Result<Integer> countOperations() {

        return Result.success(patientService.countOperationNumber());
    }

    /**
     * 统计过去七天的手术数量
     * @return 手术数量
     */
    @GetMapping("/sevenDays")
    public Result<Integer> countSurgeriesInLastSevenDays() {
        return Result.success(patientService.countSurgeriesInLastSevenDays());
    }
}